<template>
  <div class="account-list common-list-container__v2">
    <div class="account-list-main">
      <!--搜索Start-->
      <div ref="tableHeaderContainer">
        <el-input
          class="search-input mar-r-8"
          v-model="deptKeyword"
          prefix-icon="el-icon-search"
          v-trim:blur
          :placeholder="$t('common.placeholder.inputMemberNameSearch')"
          @keyup.enter.native="search"></el-input>
      </div>
      <!--搜索End-->

      <!--表格Start-->
      <div class="account-list-table mar-t-16">
        <el-table
          v-table-style
          ref="tableRef"
          v-loading="listLoading"
          header-row-class-name="common-list-table-header__v2"
          :data="dataList"
          border
          class="bbx-normal-list-box"
          :height="tableContainerHeight"
        >
          <template slot="empty">
            <BaseListForNoData
              v-show="!listLoading"
              :notice-msg="$t('common.base.tip.noData')"
            ></BaseListForNoData>
          </template>
          <template v-for="column in columns">
            <el-table-column
              v-if="column && column.show"
              show-overflow-tooltip
              :key="column.fieldName"
              :label="column.displayName"
              :min-width="column.minWidth"
              :prop="column.fieldName"
              :width="column.width"
              :resizable="true"
            >
              <template slot-scope="scope">
                <!--姓名-->
                <template v-if="column.fieldName === 'displayName'">
                  <div :class="globalIsHaveAccountViewAuth ? 'view-detail-btn' : 'view-detail-btn-disabled'" class="c-primary cur-point" @click="goUserDetail(scope.row.userId)">
                    <template v-if="isOpenData">
                      <open-data type="userName" :openid="scope.row.staffId"></open-data>
                    </template>
                    <template v-else>
                      {{ scope.row.displayName }}
                    </template>
                  </div>
                  <span v-if="scope.row.isTeamLeader" class="super-admin-label">{{$t('common.base.executiveDirector')}}</span>
                  <span v-if="scope.row.superAdmin == 2" class="super-admin-label">{{$t('common.label.admin')}}</span>
                  <div
                    v-if="scope.row.labelList && scope.row.labelList.length"
                    style="display: flex">
						      <span
                    v-for="item in scope.row.labelList"
                    :key="item.id"
                    class="super-admin-label super-admin-label-auto">{{ item.tagName }}
						      </span>
                  </div>
                </template>
                <!--未完成事件-->
                <template v-else-if="column.fieldName === 'eventCount'">
                  <div v-if="scope.row.eventCount" class="c-primary cur-point" @click="createTransTab('event', scope.row.userId)">{{ scope.row.eventCount }}</div>
                </template>
                <!--未完成工单-->
                <template v-else-if="column.fieldName === 'taskCount'">
                  <div v-if="scope.row.taskCount" class="c-primary cur-point" @click="createTransTab('task', scope.row.userId)">{{ scope.row.taskCount }}</div>
                </template>
                <!--负责客户数-->
                <template v-else-if="column.fieldName === 'customerCount'" >
                  <div v-if="scope.row.customerCount" class="c-primary cur-point" @click="createTransTab('customer', scope.row.userId)">{{ scope.row.customerCount }}</div>
                </template>
                <!--个人备件库-->
                <template v-else-if="column.fieldName === 'spareCount'">
                  <div v-if="scope.row.spareCount" class="c-primary cur-point" @click="createTransTab('stock', scope.row.userId)">{{ scope.row.spareCount }}</div>
                </template>
                <!--待审批事项-->
                <template v-else-if="column.fieldName === 'unApproveCount'">
                  <div v-if="scope.row.unApproveCount" class="c-primary cur-point" @click="createTransTab('approve', scope.row.userId)">{{ scope.row.unApproveCount }}</div>
                </template>
                <!--审批原因-->
                <template v-else-if="column.fieldName === 'show'">
                  <div v-if="scope.row.show">{{$t('common.base.manuallyDelete')}}</div>
                  <div v-else>{{$t('common.base.enableScopeDelete')}}</div>
                </template>
                <!--删除时间-->
                <template v-else-if="column.fieldName === 'deleteTime'">
                  {{scope.row[column.fieldName] | fmt_datetime}}
                </template>
                <template v-else>{{scope.row[column.fieldName]}}</template>
              </template>
            </el-table-column>
          </template>
          <el-table-column :label="$t('common.base.operation')" width="130px" fixed="right">
            <template slot-scope="scope">
              <el-button v-if="scope.row.show" type="text" @click="resume(scope.row.userId)">{{$t('common.base.reset')}}</el-button>
              <el-popover
                v-else
                placement="top-start"
                width="200"
                :content="$t('serviceProvider.accountUnreset')"
                trigger="hover">
                <el-button slot="reference" type="text" class="disable-text">{{$t('common.base.reset')}}</el-button>
              </el-popover>
              <el-button
                v-if="scope.row.eventCount ||scope.row.taskCount ||scope.row.customerCount ||scope.row.spareCount"
                type="text"
                class="transfer-btn"
                @click="createTransTab('event', scope.row.userId)"
              >{{$t('common.button.toHandOver')}}
              </el-button>
              <el-popover
                v-else
                placement="top-start"
                width="150"
                content="没有要转交的事项"
                class="disable-popover"
                trigger="hover">
                <el-button slot="reference" type="text" class="disable-text">{{$t('common.button.toHandOver')}}</el-button>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 Start -->
        <div ref="tableFooterContainer" class="table-footer bbx-normal-table-footer">
          <div class="list-info">
            <i18n path="common.base.table.totalCount" tag="span">
              <span place="count" class="level-padding">{{ page.total }}</span>
            </i18n>
          </div>
          <el-pagination
            background
            @current-change="handlePageJump"
            @size-change="handleSizeChange"
            :page-sizes="defaultTableData.defaultPageSizes"
            :page-size="page.pageSize"
            :current-page="page.pageNum"
            layout="prev, pager, next, sizes, jumper"
            :total="page.total"
          >
          </el-pagination>
        </div>
        <!-- 分页 End -->
      </div>
      <!--表格End-->
    </div>
  </div>
</template>

<script>
import { isBasicEditionHidePart, isBasicEditionHideEvent } from '@shb-lib/version';
import {isOpenData, openAccurateTab} from '@src/util/platform'
import { delColumn } from "./fields";
import Page from "@model/Page";
import { TABLE_HEIGHT_MIN } from '@src/model/const/Number';
//api
import { getDelUser, resume } from '@src/api/DepartmentApi';
import AuthMixin from '@src/mixins/authMixin'
import _ from "lodash";
import { PageRoutesTypeEnum } from "@model/enum/PageRoutesEnum";
import { defaultTableData } from '@src/util/table'
export default {
  name: "account-list",
  mixins: [ AuthMixin],
  props: {
    shareData: {
      type: Object,
      default: () => ({
        hideTopTip: false
      })
    },
  },
  computed: {
    // 基础版隐藏备件
    isBasicEditionHidePart() {
      return isBasicEditionHidePart();
    },
    // 基础版隐藏事件
    isBasicEditionHideEvent() {
      return isBasicEditionHideEvent();
    },
  },
  data() {
    return {
      defaultTableData,
      columns: delColumn, // 表头
      listLoading: false,
      deptKeyword: '',
      dataList: [], // 列表数据
      page: new Page(), // page 对象
      tableContainerHeight: `${TABLE_HEIGHT_MIN}px`, // 表格默认最小440px
    }
  },
  mounted() {
    this.columns = delColumn || [];
    if(this.isBasicEditionHidePart) {
      this.columns = delColumn.filter(item => item.fieldName !== 'spareCount');
    } else if(this.isBasicEditionHideEvent){
      this.columns = delColumn.filter(item => item.fieldName !== 'spareCount');
    }
    // 查询
    this.search();
    let that_ = this;
    // 监听切换后需要重新计算列表高度 后续可以用activated生命周期替换
    window.addEventListener('message', (event)=> {
      const {action} = event.data;
      if (action === 'shb.frame.activatedPage'){
        that_.$nextTick(()=> {
          that_.knowTableContainerHeight();
        })
      }
    });
    this.$nextTick(()=> {
      this.knowTableContainerHeight()
      window.onresize = _.debounce(()=>{
        that_.knowTableContainerHeight()
      }, 500)
    })
  },
  methods: {
    async search() {
      try {
        this.listLoading = true;
        let { pageNum, pageSize } = this.page;
        let data = {
          pageNum,
          pageSize,
          roleType: 'delauth',
          type: 0,
        }
        if(this.deptKeyword) data.keyword = this.deptKeyword;
        let res = await getDelUser(data);
        let { list } = res;
        if (!list) data.page = new Page();
        this.page.merge(res);
        this.dataList = list || [];
      } catch (error) {
        console.error('get account list error', error);
      } finally {
        this.listLoading = false;
      }
    },
    // 转交详情页
    createTransTab(type, userId) {
      let fromId = window.frameElement.getAttribute('id');
      /*this.$platform.openTab({
        id: 'M_JOBTRANSFER_DETAIL',
        title: '转交详情',
        close: true,
        url: `/jobtransfer/view?type=${type}&userId=${userId}`,
        fromId
      });*/
      openAccurateTab({
        type: PageRoutesTypeEnum.PageJobtransferView,
        params: `type=${type}&userId=${userId}`,
        fromId
      })
    },
    /* 跳转 用户详情页 */
    goUserDetail(id) {
      if (!window.frameElement) return;
      if (!this.globalIsHaveAccountViewAuth) return;// 没有查看权限直接返回
      let fromId = window.frameElement.getAttribute('id');
      /*this.$platform.openTab({
        id: `tab_department_view_${id}`,
        title: '成员详情',
        close: true,
        reload: true,
        url: `/security/user/view/${id}?from=department`,
        fromId
      });*/
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSecurityUserView,
        key: id,
        reload: true,
        params: 'from=department',
        fromId,
      })
    },
    // 恢复账号
    async resume(userId) {
      try {
        if (await this.$confirm('确定要恢复该账号吗？')) {
          const { status, message } = await resume({ userId });
          let isSuccess = status === 0;
          this.$notify({
            title: isSuccess ? this.$t('common.base.success') : this.$t('common.base.fail'),
            message: isSuccess ? this.$t('common.base.tip.recoverAccountSuccess') : message,
            type: isSuccess ? 'success' : 'error'
          });
          // 刷新页面
          isSuccess && this.resetSearch();
        }
      } catch (error) {
        console.error(error);
      }
    },
    // 页码跳转
    handlePageJump(pageNum) {
      this.page.pageNum = pageNum;
      this.search();
    },
    // 页数修改
    handleSizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.page.pageNum = 1;
      // 列表查询
      this.search();
    },
    // 重置
    resetSearch() {
      this.page.pageNum = 1;
      // 列表查询
      this.search();
    },
    // 表格高度计算
    knowTableContainerHeight(){
      let min = TABLE_HEIGHT_MIN; // 表格默认最小440
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let topTip = this.shareData?.hideTopTip ? 0 : 48;
        min = window_ - header * 1  - footer * 1 - 12 - 16 * 3 - topTip; // 12:表格的距离上面的margin距离；16：整个页面的上下两个padding和一个搜索框距离表格的距离；48是上面黄色的提示的高度以及距离下面的margin
        min = min > TABLE_HEIGHT_MIN ? min : TABLE_HEIGHT_MIN;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`)
    },
  },
  watch: {
    shareData:{
      deep: true,
      handler(val) {
        if(val.hideTopTip) {
          this.knowTableContainerHeight();// 监听头部提示是否隐藏，隐藏的话调用
        }
      }
    }
  },
}
</script>

<style lang="scss" scoped>
.account-list {
  height: 100%;
  overflow: auto;
  border-radius: 4px;
  padding: 0;
  &-main {
    margin-right: 12px;
    background: white;
    padding: 12px 12px 0;
  }
  .search-input {
    width: 205px;
  }
  &-table {
    background-color: #fff;
    border-radius: 4px;
    .c-primary {
      color:$color-primary
    }
    .disable-text {
      cursor: not-allowed;
      color: #c0c4cc !important;
    }
    .disable-popover, .transfer-btn {
      margin-left: 12px;
    }
    .super-admin-label {
      background: rgba(255, 146, 0, 0.16);
      border-radius: 4px;
      border: 1px solid rgba(255, 146, 0, 0.16);
      color: #FF9200;
      padding: 0px 10px;
      font-size: 10px;
      display: inline-block;
      height: 24px;
      line-height: 24px;
      margin: 8px 5px;
    }
    .super-admin-label-auto{
      background: $color-primary-light-1;
      border: 1px solid $color-primary-light-1;
      color:$color-primary-light-6
    }
    .table-footer {
      display: flex;
      justify-content: space-between;
      padding: 0px 10px 10px 10px;
      background: #fff;
      border-radius: 0 0 4px 4px;

      .list-info {
        font-size: 13px;
        line-height: 32px;
        margin: 0;
        color: #767e89;

        .iconfont {
          position: relative;
          top: 1px;
        }
      }

      .el-pagination__jump {
        margin-left: 0;
      }
    }
  }
}
</style>